import 'dart:collection';
import 'package:flutter_deer/util/speak/tts_base_engine.dart';
import 'package:flutter_tts/flutter_tts.dart';

class TtsEngineDefault extends ITtsBaseEngine  {
  factory TtsEngineDefault() => _instance;

  TtsEngineDefault._internal();

  // 单例实例
  static final TtsEngineDefault _instance = TtsEngineDefault._internal();

  // 核心组件
  late FlutterTts _flutterTts;
  final Queue<String> _speechQueue = Queue();
  bool _isSpeaking = false;

  // 回调函数
  Function(dynamic)? _errorCallback;
  Function()? _onComplete;

  /// 初始化 TTS 引擎
  Future<void> init({
    Function(dynamic)? onError,
    Function()? onComplete,
  }) async {
    _flutterTts = FlutterTts();

    final languages = await _flutterTts.getLanguages;
    print('languages: $languages');

    // 设置中文
    await _flutterTts.setLanguage('zh-CN');
    await _flutterTts.setSpeechRate(0.5);
    await _flutterTts.setPitch(1.0);
    await _flutterTts.setVolume(1.0);

    // 回调注册
    _errorCallback = onError;
    _onComplete = onComplete;

    _flutterTts.setErrorHandler((msg) {
      _handleError(msg);
    });

    _flutterTts.setCompletionHandler(() {
      _processQueue();
      print('TtsEngineDefault onComplete');
      _onComplete?.call();
    });
  }

  /// 播报文本（支持队列）
  @override
  Future<void> speak(String text) async {
    _speechQueue.add(text);
    if (!_isSpeaking) {
      await _processQueue();
    }
  }

  /// 处理队列中的下一个任务
  Future<void> _processQueue() async {
    if (_speechQueue.isEmpty) {
      _isSpeaking = false;
      return;
    }

    _isSpeaking = true;
    final text = _speechQueue.removeFirst();
    print('TtsEngineDefault speak: $text');
    try {
      await _flutterTts.speak(text);
    } catch (e) {
      _handleError(e);
    }
  }

  /// 设置音量 (0.0~1.0)
  Future<void> setVolume(double volume) async {
    await _flutterTts.setVolume(volume);
  }

  /// 设置语速 (0.0~1.0)
  Future<void> setSpeechRate(double rate) async {
    await _flutterTts.setSpeechRate(rate);
  }

  /// 设置音调 (0.0~2.0)
  Future<void> setPitch(double pitch) async {
    await _flutterTts.setPitch(pitch);
  }

  /// 切换语音
  Future<void> setVoice(Map<String, String> voice) async {
    await _flutterTts.setVoice(voice);
  }

  /// 停止播放
  Future<void> stop() async {
    await _flutterTts.stop();
    _isSpeaking = false;
  }

  /// 错误处理
  void _handleError(dynamic error) {
    _isSpeaking = false;
    _errorCallback?.call(error);
    print('TtsEngineDefault error: $error');
  }
}
